package com.jt.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{
    @Override
    public String upload(MultipartFile file) {
        String fileName=file.getOriginalFilename();
        if(!fileName.toLowerCase().matches("^.+\\.(jpg|png|gif)$")) return null;
        try {
            BufferedImage bufferedImage=ImageIO.read(file.getInputStream());
            int height=bufferedImage.getHeight();
            int width=bufferedImage.getWidth();
            if(height==0||width==0)return null;

            MultipartFile newFile=file;
            String newFileName = newFile.getOriginalFilename();
            String dirPath = "E:/nodejs/vueproject/aj-cloud/src/assets/images/";
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String uuid= UUID.randomUUID().toString().replace("-","");
            int index=newFileName.lastIndexOf(".");
            String fileType=newFileName.substring(index);
            String realFileName=uuid+fileType;
            String filePath=dirPath+realFileName;
            file.transferTo(new File(filePath));

            return realFileName;

        } catch (IOException e) {
            e.printStackTrace();
            return null;//如果程序执行报错,则返回null
        }
    }
}
